// ---------------------------------------------------------------------
//
// -- 平台相关
// -- author £
//
// ---------------------------------------------------------------------

const CommonUtil = require('CommonUtil'),
    CommonInfo = require('CommonInfo'),
    WGUtil = require('WGUtil'),
    AppInfo = require('AppInfo'),
    GameConfig = require('GameConfig');

const SKIP_AUTH_TIME = 8,
    SKIP_AUTH_STR = '长时间没有授权，系统自动跳过授权。(注：如多次点击未响应，请升级最新版本微信)';

let Platform = {
    hasSub: true,

    checkUpdate: function () {
        if (!AppInfo.wx) return;

        let um = wx.getUpdateManager();

        um.onCheckForUpdate(function (res) {
            console.log('onCheckForUpdate', res);
            if (res.hasUpdate) {
                wx.showLoading({
                    title: '更新最新版本中',
                    mask: true,
                });

                try {
                    um.applyUpdate();
                } catch (e) {
                    wx.hideLoading({});
                    wx.showModal({
                        title: '系统',
                        content: '对不起，更新版本失败。',
                        showCancel: false
                    });
                }
            }
        });
        um.onUpdateReady(function (res) {
            wx.hideLoading({});
            wx.showLoading({
                title: '更新完成',
                mask: true,
            });

            try {
                um.applyUpdate();
            } catch (e) {
                console.log('applyUpdate again fail');
            }

            CommonUtil.delay(
                new cc.Node(),
                8,
                function () {
                    wx.hideLoading({});
                    wx.showModal({
                        title: '系统',
                        content: '游戏已更新至最新版本，尝试重启失败，请手动重启。',
                        showCancel: false
                    });
                    CommonUtil.delay(
                        new cc.Node(),
                        3,
                        function () {
                            wx.exitMiniProgram();
                        }, this
                    );
                }, this
            );
        });
        um.onUpdateFailed(function (res) {
            wx.hideLoading({});
            wx.showModal({
                title: '系统',
                content: '对不起，更新版本失败。',
                showCancel: false
            });
        });
    },

    updateSub: function (tex, sp) {
        if (!this.hasSub) return;
        if (!AppInfo.wx) return;
        if (!sharedCanvas) return;

        tex.releaseTexture();
        tex.initWithElement(sharedCanvas);
        tex.handleLoadedTexture();
        sp.spriteFrame = new cc.SpriteFrame(tex);
    },

    setHead: function (url, id, head) {
        if (!head) return;

        url = url.substring(0, url.lastIndexOf('/') + 1) + '132';

        let self = require('CommonInfo').self(id);

        self ?
            require('TextureManager').getTexture(
                'common',
                url,
                'head', head
            ) :
            require('TextureManager').getTexture(
                require('TextureManager').getCurKey(),
                url,
                'head' + id, head
            );
    },

    selfHead: function (head) {
        require('TextureManager').getTexture(
            'common',
            '',
            'head', head
        );
    },

    scaleSharedCanvas: function () {
        // if (!AppInfo.wx) return;

        // WGUtil.scaleSharedCanvas();
    },

    exitMiniProgram: function () {
        if (!AppInfo.wx) return;

        wx.exitMiniProgram();
    },

    setAuth: function (sCb, fCb) {
        wx.openSetting({
            success: (function (res) {
                if (!res.authSetting['scope.userInfo']) {
                    fCb();
                    return;
                }

                sCb();
            }).bind(this),
            fail: (function () {
                fCb();
            }).bind(this),
        });
    },

    previewImage: function () {
        if (!AppInfo.wx) return;

        let url = WGUtil.getWGShareUrl();

        wx.previewImage({
            urls: [url],
            success: function (res) {
                console.log('previewImage s:', res);
            },
            fail: function (res) {
                console.log('previewImage f:', res);
            }
        });
    },

    nextRecommand: function () {
        if (!AppInfo.wx) return;

        return WGUtil.getWGShareIcon();
    },

    recommandIndex: function () {
        console.log('recommandIndex:', WGUtil.recommandIndex());
        return WGUtil.recommandIndex();
    },

    setRecommandData: function (list) {
        WGUtil.setRecommandData(list);
    },

    getLaunchData: function () {
        let result = wx.getLaunchOptionsSync();

        console.log('wx.getLaunchOptionsSync', result);

        return result;
    },

    onPlatformShow: function (cb) {
        wx.onShow(cb);
    },

    startShare: function (cb, successCb) {
        if (!AppInfo.wx) return;

        wx.showShareMenu({
            withShareTicket: true
        });
        wx.onShareAppMessage((function (shareTickets, groupMsgInfos) {
            if (cb)
                cb();

            return this._getShareObj(successCb, false);
        }).bind(this));
    },

    stopShare: function () {

    },

    share: function (successCb, query) {
        if (!AppInfo.wx) return;

        if (!GameConfig.shareConfiged) {
            GameConfig.userProto.queryShareData(
                2,
                (this.getShareConfig).bind(this)
            );
        }

        wx.shareAppMessage(this._getShareObj(successCb, query));
    },

    getShareConfig: function (xhrData) {
        if (xhrData.code) return;

        let data = xhrData.data;

        require('GameText').SHARE_STR = data.content;
        GameConfig.SHARE_IMAGE_URL = data.img;
        GameConfig.shareConfiged = true;
        console.log('update share data');
    },

    shareScore: function (successCb, query) {
        if (!AppInfo.wx) return;

        if (!GameConfig.shareScoreConfiged) {
            GameConfig.userProto.queryShareData(
                3,
                (this.getShareScoreConfig).bind(this)
            );
        }

        wx.shareAppMessage(this._getShareObj(successCb, query, true));
    },

    getShareScoreConfig: function (xhrData) {
        if (xhrData.code) return;

        let data = xhrData.data;

        require('GameText').SHARE_SCORE = data.content;
        GameConfig.SHARE_IMAGE_URL = data.img;
        GameConfig.shareScoreConfiged = true;
        console.log('update share score data');
    },

    shareRCoin: function (successCb) {
        if (!AppInfo.wx) return;

        wx.shareAppMessage({
            title: require('GameText').shareReviveTxt,
            imageUrl: require('GameConfig').rCoinImgUrl,
            query: 'shareRCoinId=' + CommonInfo.shareRCoinId +
                '&rCoinSender=' + CommonInfo.userID(),
            success: function (res) {
                console.log('shareRCoin success', res);

                if (successCb)
                    successCb(res);
            },
            fail: (function (res) {
                console.log('shareRCoin fail', res);
            }).bind(this)
        });
    },

    _getShareObj: function (successCb, query, shareScore) {
        let ActivityInfo = require('ActivityInfo'),
            isHoliday = ActivityInfo.isHoliday(),
            t = isHoliday ?
                ActivityInfo.SHARE_STR :
                (shareScore ?
                    (require('GameText').SHARE_SCORE).replace(
                        '\{0\}', CommonInfo.bestScore + '') :
                    require('GameText').SHARE_STR),
            result = {
                title: t,
                imageUrl: isHoliday ? ActivityInfo.SHARE_IMAGE_URL :
                    require('GameConfig').SHARE_IMAGE_URL,
                success: function (res) {
                    console.log('shareroom success', res);

                    if (successCb)
                        successCb(res);
                },
                fail: (function (res) {
                    console.log('shareroom fail', res);
                }).bind(this)
            };

        if (query) {
            result.query = 'gurl=' + CommonInfo.gameUrl + '&id=' + CommonInfo.record;
        }

        return result;
    },

    uploadUserData: function (data) {
        if (!AppInfo.wx) return;

        wx.setUserCloudStorage({
            KVDataList: [
                { key: 'userid', value: CommonInfo.userID() + '' },
                { key: 'history_best', value: data.score + '' },
                { key: 'city', value: CommonInfo.city() },
                { key: 'province', value: CommonInfo.province() },
                { key: 'sex', value: CommonInfo.sex() + '' }
            ],
            complete: function (res) {
                console.log(res);
            },
        });
    },

    postMessage: function (data) {
        if (!AppInfo.wx) return;

        wx.postMessage(data);
    },

    createBannerAd: function () {
        if (!AppInfo.wx) return;
        if (!wx.createBannerAd) return;

        let info = wx.getSystemInfoSync();
        console.log('info.SDKVersion', info.SDKVersion);
        if (require('CommonUtil').compareVersion(info.SDKVersion, '2.0.4') < 0)
            return;

        if (this.bannerAd)
            this.bannerAd.offLoad(this._bannerLoaded);

        this.bannerAd = wx.createBannerAd({
            adUnitId: GameConfig.bannerID,
            style: {
                left: 0,
                top: 0,
                width: info.screenWidth
            }
        });

        this._bannerLoaded = (this.onBannerLoaded).bind(this);
        this.bannerAd.onLoad(this._bannerLoaded);
        // this.bannerAd.show();
    },

    onBannerLoaded: function () {
        let info = wx.getSystemInfoSync();
        // console.log('bannerAd size');
        // console.log(this.bannerAd.style.realWidth, this.bannerAd.style.realHeight);
        this.bannerAd.style.left = (info.screenWidth -
            this.bannerAd.style.realWidth) * 0.5;
        this.bannerAd.style.top = info.screenHeight -
            this.bannerAd.style.realWidth * 0.287;
    },

    showBannerAd: function () {
        this.createBannerAd();

        if (!this.bannerAd) return;
        if (!this.adEnable()) return;

        this.bannerAd.show();
    },

    hideBannerAd: function () {
        if (!this.bannerAd) return;
        if (!this.adEnable()) return;

        this.bannerAd.offLoad(this._bannerLoaded);
        this.bannerAd.hide();
        this.bannerAd = null;
    },

    createRewardedVideoAd: function () {
        if (!AppInfo.wx) return;
        if (!wx.createRewardedVideoAd) return;

        let info = wx.getSystemInfoSync();

        if (require('CommonUtil').compareVersion(info.SDKVersion, '2.0.4') < 0)
            return;

        this.videoAd = wx.createRewardedVideoAd({
            adUnitId: GameConfig.videoID,
        });
    },

    showVideoAd: function (close, error) {
        this.createRewardedVideoAd();

        if (!this.videoAd) return;
        if (!this.videoAdEnable()) return;

        this._adClose = close;
        this._adError = error;
        this._onAdLoad = (this.onVideoLoad).bind(this);
        this._onAdClose = (this.onVideoClose).bind(this);
        this._onAdError = (this.onVideoError).bind(this);
        this.videoAd.onError(this._onAdError);
        this.videoAd.onClose(this._onAdClose);
        this.videoAd.onLoad(this._onAdLoad);

        if (this._videoLoaded)
            this.videoAd.show();
    },

    onVideoLoad: function () {
        console.log('onVideoLoad');
        if (this._videoLoaded) return;

        this.videoAd.show();
        this._videoLoaded = true;
    },

    onVideoClose: function () {
        console.log('onVideoClose');
        if (!this.videoAd) return;

        if (this._onAdLoad)
            this.videoAd.offLoad(this._onAdLoad);
        if (this._onAdError)
            this.videoAd.offError(this._onAdError);
        if (this._onAdClose)
            this.videoAd.offClose(this._onAdClose);

        if (!this._adClose) return;

        this._adClose();
        this.videoAd.load();
    },

    onVideoError: function () {
        console.log('onVideoError');
        if (!this.videoAd) return;

        if (this._onAdLoad)
            this.videoAd.offLoad(this._onAdLoad);
        if (this._onAdError)
            this.videoAd.offError(this._onAdError);
        if (this._onAdClose)
            this.videoAd.offClose(this._onAdClose);

        if (!this._adError) return;

        this._adError();
        this.videoAd.load();
    },

    hideVideoAd: function () {
        if (!this.videoAd) return;
        if (!this.videoAdEnable()) return;

        this.videoAd.load().catch((function () {
            console.log('video load error, disable video func');
            this._videoError = true;
        }).bind(this));
        // this.videoAd.load()
    },

    adEnable: function () {
        if (!AppInfo.wx) return false;

        return require('CommonUtil').compareVersion(
            wx.getSystemInfoSync().SDKVersion, '2.0.4') >= 0;
    },

    videoAdEnable: function () {
        if (!AppInfo.wx) return false;
        if (this._videoError) return false;

        return require('CommonUtil').compareVersion(
            wx.getSystemInfoSync().SDKVersion, '2.0.4') >= 0;
    },

    UserProto: cc.Class({
        name: 'UserProto',

        properties: {

        },

        initCtor: function () {
            this.domain = 'https://mggf.leshu.com/api/v1/';
            // this.domain = 'http://10.10.170.8:894/api/v1/';
            this.LOGIN_CODE = 'weixin/checkCode';
            this.LOGIN_DATA = 'weixin/refreshUserInfo';
            this.QUERY_USERINFO = 'Serach/serachByCharid';
            this.QUERY_MONEY = 'Serach/serGadByCharid';
            this.QUERY_WORLD_RANK = 'rank/historyBestList';
            this.QUERY_REGION_RANK = 'Charts/chartByRegional';
            this.QUERY_RANK_DETAIL = 'Charts/chartByregion';
            this.QUERY_KEYS = 'Serach/getCharactBykeyword';
            this.QUERY_BEST = 'rank/todayBestScore';
            this.QUERY_GAMERESULT = 'Settlement/getEndGameInfo';
            this.QUERY_CONFIG = 'game/getSettingInfo';
            this.QUERY_SHARE_DATA = 'game/shareData';
            this.QUERY_USER_ITEM = 'item/userData';
            this.GET_SHARE_ITEM = 'game/shareRewardFetch';
            this.CHANGE_ITEM = 'item/itemChange2';
            this.SAVE_SCORE = 'rank/saveScore';
            this.QUERY_RANK_LIST = 'rank/getRankList';
            this.QUERY_HISTORY_BEST = 'rank/historyBestList';
            this.QUERY_RECOMMAND_DATA = 'game/recommendData',

            this._m = null;
            this._loginXHR = null;
            this._queryUserXHR = null;
            this._queryMoneyXHR = null;
            this._queryRankXHR = null;
            this._queryKeysXHR = null;
            this._queryBestXHR = null;
            this._queryGameResultXHR = null;
            this._queryConfigXHR = null;
            this._queryShareDataXHR = null;
            this._queryItemXHR = null;
            this._getShareItemXHR = null;
            this._changeItemXHR = null;
            this._saveScoreXHR = null;
            this._recommandDataXHR = null;
            this._code = null;

            this._token = '';
        },

        ctor: function () {
            this.initCtor();
        },

        bindM: function (m) {
            this.stop();
            this._m = m;
        },

        unbindM: function (m) {
            if (m !== this._m) return;

            this.stop();
            this._m = null;
        },

        stop: function () {
            if (this._loginXHR)
                this._loginXHR.abort();
            if (this._queryUserXHR)
                this._queryUserXHR.abort();
            if (this._queryMoneyXHR)
                this._queryMoneyXHR.abort();
            if (this._queryRankXHR)
                this._queryRankXHR.abort();
            if (this._queryKeysXHR)
                this._queryKeysXHR.abort();
            if (this._queryBestXHR)
                this._queryBestXHR.abort();
            if (this._queryGameResultXHR)
                this._queryGameResultXHR.abort();
            if (this._queryConfigXHR)
                this._queryConfigXHR.abort();
            if (this._queryShareDataXHR)
                this._queryShareDataXHR.abort();
            if (this._queryItemXHR)
                this._queryItemXHR.abort();
            if (this._getShareItemXHR)
                this._getShareItemXHR.abort();
            if (this._changeItemXHR)
                this._changeItemXHR.abort();
            if (this._saveScoreXHR)
                this._saveScoreXHR.abort();
            if (this._recommandDataXHR)
                this._recommandDataXHR.abort();
        },

        queryRecommandData: function (cb) {
            this._recommandDataXHR =
                CommonUtil.createXHR(
                    this._recommandDataXHR,
                    'POST',
                    this.domain + this.QUERY_RECOMMAND_DATA,
                    true,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token,
                    cb
                );
        },

        queryConfig: function (cb) {
            this._queryConfigXHR =
                CommonUtil.createXHR(
                    this._queryConfigXHR,
                    'POST',
                    this.domain + this.QUERY_CONFIG,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token,
                    cb
                );
        },

        queryGameResult: function (charid, uniqid) {
            this._queryGameResultXHR =
                CommonUtil.createXHR(
                    this._queryGameResultXHR,
                    'POST',
                    this.domain + this.QUERY_GAMERESULT,
                    true,
                    'charid=' + charid +
                    '&uniqid=' + uniqid,
                    (function (xhrData) {
                        if (xhrData && xhrData.errcode) {
                            return;
                        }

                        if (this._m && this._m.getQueryGameResult)
                            this._m.getQueryGameResult(xhrData);
                    }).bind(this),
                );
        },

        queryBest: function () {
            this._queryBestXHR =
                CommonUtil.createXHR(
                    this._queryBestXHR,
                    'POST',
                    this.domain + this.QUERY_BEST,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&user_id=' + CommonInfo.userID() +
                    '&token=' + this._token,
                    function (xhrData) {
                        if (xhrData.code) return;

                        if (xhrData.data.today_best_score > CommonInfo.dayBestScore)
                            CommonInfo.dayBestScore = xhrData.data.today_best_score;
                    }
                );
        },

        saveScore: function () {
            if (!CommonInfo.userRegisted) return;

            this._saveScoreXHR =
                CommonUtil.createXHR(
                    this._saveScoreXHR,
                    'POST',
                    this.domain + this.SAVE_SCORE,
                    true,
                    'game_id=' + GameConfig.gameId +
                    '&user_id=' + CommonInfo.userID() +
                    '&score=' + CommonInfo.bestScore +
                    '&time=' + Math.floor(new Date().getTime() * 0.001) +
                    '&token=' + this._token,
                );
        },

        queryRankDetial: function (province, charid) {
            this._queryRankXHR =
                CommonUtil.createXHR(
                    this._queryRankXHR,
                    'POST',
                    this.domain + this.QUERY_RANK_DETAIL,
                    false,
                    'province=' + province +
                    '&charid=' + charid,
                    (function (xhrData) {
                        if (xhrData && xhrData.errcode) {
                            return;
                        }

                        if (this._m && this._m.getQueryRegionDetial)
                            this._m.getQueryRegionDetial(xhrData);
                    }).bind(this),
                );
        },

        queryWorldRank: function (cb) {
            this._queryRankXHR =
                CommonUtil.createXHR(
                    this._queryRankXHR,
                    'POST',
                    this.domain + this.QUERY_RANK_LIST,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&rank_type=3' +
                    '&region_id=0' +
                    '&token=' + this._token +
                    '&page_count=100' +
                    '&page_num=1',
                    cb
                );
        },

        queryHistoryBest: function (cb) {
            this._queryRankXHR =
                CommonUtil.createXHR(
                    this._queryRankXHR,
                    'POST',
                    this.domain + this.QUERY_HISTORY_BEST,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token,
                    cb
                );
        },

        queryRegionRank: function (charid) {
            this._queryRankXHR =
                CommonUtil.createXHR(
                    this._queryRankXHR,
                    'POST',
                    this.domain + this.QUERY_REGION_RANK,
                    false,
                    'charid=' + charid,
                    (function (xhrData) {
                        if (xhrData && xhrData.errcode) {
                            return;
                        }

                        if (this._m && this._m.getQueryRegionRank)
                            this._m.getQueryRegionRank(xhrData);
                    }).bind(this),
                );
        },

        queryMoney: function (charid) {
            this._queryMoneyXHR =
                CommonUtil.createXHR(
                    this._queryMoneyXHR,
                    'POST',
                    this.domain + this.QUERY_MONEY,
                    false,
                    'charid=' + charid,
                    (function (xhrData) {
                        if (xhrData && xhrData.errcode) {
                            return;
                        }

                        if (this._m && this._m.getQueryMoney)
                            this._m.getQueryMoney(xhrData);
                    }).bind(this),
                );
        },

        queryUserInfo: function (cmd, charids) {
            this._queryUserXHR =
                CommonUtil.createXHR(
                    this._queryUserXHR,
                    'POST',
                    this.domain + this.QUERY_USERINFO,
                    true,
                    'charids=' + charids.toString(),
                    (function (xhrData) {
                        if (xhrData && xhrData.errcode) {
                            return;
                        }

                        if (this._m && this._m.getQueryUserInfo)
                            this._m.getQueryUserInfo(cmd, xhrData);
                    }).bind(this),
                );
        },

        queryKeys: function (cmd, charids, keys) {
            this._queryKeysXHR =
                CommonUtil.createXHR(
                    this._queryKeysXHR,
                    'POST',
                    this.domain + this.QUERY_KEYS,
                    true,
                    'charids=' + charids.toString() +
                    '&queryKey=' + keys.toString(),
                    (function (xhrData) {
                        if (this._m && this._m.getQueryKeys)
                            this._m.getQueryKeys(cmd, xhrData);
                    }).bind(this),
                );
        },

        queryShareData: function (type, cb, eCb) {
            this._queryShareDataXHR =
                CommonUtil.createXHR(
                    this._queryShareDataXHR,
                    'POST',
                    this.domain + this.QUERY_SHARE_DATA,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token +
                    '&share_type=' + type,
                    cb, eCb
                );
        },

        queryItem: function (cb, eCb) {
            this._queryItemXHR =
                CommonUtil.createXHR(
                    this._queryItemXHR,
                    'POST',
                    this.domain + this.QUERY_USER_ITEM,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token,
                    cb, eCb
                );
        },

        getShareItem: function (cb, eCb) {
            this._getShareItemXHR =
                CommonUtil.createXHR(
                    this._getShareItemXHR,
                    'POST',
                    this.domain + this.GET_SHARE_ITEM,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token +
                    '&share_id=' + CommonInfo.shareRCoinId,
                    cb, eCb
                );
        },

        changeItem: function (id, d, cb, eCb) {
            this._changeItemXHR =
                CommonUtil.createXHR(
                    this._changeItemXHR,
                    'POST',
                    this.domain + this.CHANGE_ITEM,
                    true,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token +
                    '&items=' + id + ':' + d,
                    cb, eCb
                );
        },

        login: function (finishCb) {
            this._finishCb = finishCb;

            if (this._loginXHR)
                this._loginXHR.abort();

            wx.login({
                success: (function (res) {
                    let postObj = {};

                    console.log('wx.login' + res.code);
                    // return;
                    this._code = res.code;
                    postObj.game_id = GameConfig.gameId;
                    postObj.wx_code = res.code;
                    postObj.time = Math.floor(new Date().getTime() * 0.001);
                    postObj.sign = CommonUtil.sign(postObj);
                    this._loginXHR =
                        CommonUtil.createXHR(
                            this._loginXHR,
                            'POST',
                            this.domain + this.LOGIN_CODE,
                            false,
                            'game_id=' + postObj.game_id +
                            '&wx_code=' + postObj.wx_code +
                            '&time=' + postObj.time +
                            '&sign=' + postObj.sign,
                            (function (xhrData) {
                                if (xhrData.code) {
                                    this._loginFail();
                                    return;
                                }

                                CommonInfo.loginFinish(xhrData.data);
                                this._token = xhrData.data.token;

                                if (CommonInfo.validateCacheUserInfo()) {
                                    console.log('cache userInfo valid');
                                    CommonInfo.doCacheLogin();

                                    if (this._m && this._m.loginFinish)
                                        this._m.loginFinish();

                                    if (this._finishCb)
                                        this._finishCb();

                                    return;
                                }

                                if (wx.createUserInfoButton) {
                                    console.log('new version');
                                    let delay_node = new cc.Node();
                                    let UIManager = require('UIManager');
                                    let button = wx.createUserInfoButton({
                                        type: 'text',
                                        text: '',
                                        style: {
                                            left: 0,
                                            top: 0,
                                            width: UIManager.getRealW(),
                                            height: UIManager.getRealH(),
                                            lineHeight: 600,
                                            backgroundColor: '#00000000',
                                            color: '#00000000',
                                            textAlign: 'center',
                                            fontSize: 40,
                                            borderRadius: 4
                                        }
                                    });

                                    button.onTap((res) => {
                                        delay_node.stopAllActions();

                                        if (!res.userInfo) {
                                            button.hide();
                                            button.destroy();

                                            if (this._m && this._m.refuseAuth)
                                                this._m.refuseAuth();

                                            return;
                                        }

                                        if (this._m && this._m.clickAuthFinish)
                                            this._m.clickAuthFinish();

                                        button.hide();
                                        button.destroy();
                                        this._dealUserInfo(res);
                                    });
                                    button.show();

                                    if (this._m && this._m.requireClickAuth)
                                        this._m.requireClickAuth();

                                    CommonUtil.delay(
                                        delay_node,
                                        SKIP_AUTH_TIME,
                                        function () {
                                            button.hide();
                                            button.destroy();
                                            require('Alert').show(
                                                null,
                                                SKIP_AUTH_STR
                                            );

                                            if (this._m && this._m.refuseAuth)
                                                this._m.refuseAuth();
                                        }, this
                                    );

                                    return;
                                }

                                console.log('old version');
                                wx.authorize({
                                    scope: 'scope.userInfo',
                                    success: (function (res) {
                                        this.getUserInfo();
                                    }).bind(this),
                                    fail: (function (res) {
                                        if (this._m && this._m.gotoSetAuth)
                                            this._m.gotoSetAuth();
                                        // if (this._m && this._m.refuseAuth)
                                        //         this._m.refuseAuth();
                                    }).bind(this),
                                });
                            }).bind(this),
                            (this._loginFail).bind(this)
                        );
                }).bind(this),
                fail: (function (res) {
                    console.log('login fail:', res);
                    this._loginFail();
                }).bind(this)
            });
        },

        getUserInfo: function () {
            wx.getUserInfo({
                lang: 'zh_CN',
                success: (function (res) {
                    this._dealUserInfo(res);
                }).bind(this),
                fail: (function (res) {
                    this._reconnectLobby();
                }).bind(this)
            });
        },

        _loginFail: function (evt) {
            console.log('_loginFail', evt);
            if (this._loginXHR)
                this._loginXHR.abort();

            if (this._m && this._m.loginFail)
                this._m.loginFail();
        },

        _reconnectLobby: function () {
            if (this._m && this._m._reconnectLobby)
                this._m._reconnectLobby();
        },

        _dealUserInfo: function (res) {
            console.log('_dealUserInfo:', res);
            CommonInfo.setWXUserInfo(res.userInfo);
            this._loginXHR =
                CommonUtil.createXHR(
                    this._loginXHR,
                    'POST',
                    this.domain + this.LOGIN_DATA,
                    false,
                    'game_id=' + GameConfig.gameId +
                    '&token=' + this._token +
                    '&wx_data=' + res.encryptedData +
                    '&wx_iv=' + res.iv,
                    (function (xhrData) {
                        if (xhrData.code) {
                            this._loginFail();
                            return;
                        }

                        console.log('_m.loginFinish');
                        if (this._m && this._m.loginFinish)
                            this._m.loginFinish(xhrData);

                        if (this._finishCb)
                            this._finishCb();
                    }).bind(this),
                    (this._loginFail).bind(this)
                );

        },
    }),
};

module.exports = Platform;